<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width:200px;
            height:200px;
            position: absolute;
            background: red;
        }
    </style>

</head>
<body>
    <div class="box" id="box"></div>

    <script>
        var box=document.querySelector('#box')
        box.onmousedown=function(){
            // console.log(1);
            
            
            window.onmousemove=function(e){
                // console.log(2);
                
                e=e||window.event;
                var x=e.clientX-box.offsetWidth/2;
                var y=e.clientY-box.offsetHeight/2;

                if(x<=0){x=0;}
                if(y<=0){y=0;}

                if(x>=window.innerWidth-box.offsetWidth){x=window.innerWidth-box.offsetWidth;}
                if(y>=window.innerHeight-box.offsetHeight){y=window.innerHeight-box.offsetHeight;}
                console.log(x);
                console.log(y);

                box.style.left = x + 'px';
                box.style.top = y + 'px'
            }
        }
        window.onmouseup=function(){
            window.onmousemove=null;
        }



    </script>



</body>
</html>